package edu.hnnu.sport_event.service;

import edu.hnnu.sport_event.entity.Event;
import edu.hnnu.sport_event.entity.Score;
import edu.hnnu.sport_event.entity.SignUp;
import edu.hnnu.sport_event.entity.Student;
import edu.hnnu.sport_event.mapper.EventMapper;
import edu.hnnu.sport_event.mapper.StudentMapper;
import edu.hnnu.sport_event.utils.InsertError;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EventService implements BasicService<Event> {

    @Resource EventMapper eventMapper;
    @Resource StudentMapper studentMapper;
    @Resource RankingService rankingService;
    @Resource SignUpService signUpService;

    @Override
    public int insert(Event event) {
        return eventMapper.insert(event);
    }

    // 删除event同时删除报名表和成绩表
    @Override
    @Transactional
    public int delete(int id) {
        Score score = rankingService.selectByEventId(id);
        SignUp signUp = signUpService.selectByEventId(id);
        if (null != score) rankingService.delete(score.getId());
        if (null != signUp) signUpService.delete(signUp.getId());
        return eventMapper.delEvent(id);
    }

    @Override
    public int modify(Event event) {
        return eventMapper.modify(event);
    }

    @Override
    public Event select(int id) {
        return eventMapper.selectOne(id);
    }

    public List<Event> selectAll(Integer pn) {
        // 在这里做分页处理
        return eventMapper.selectEvents(1);
    }

    // 学生报名运动项目
    @Transactional
    public Integer signUp(int studentId, int eventId) {
        // 是否以已经报过名
        Integer res = eventMapper.selectSignUpInfo(studentId, eventId);
        if (null == res) {
            // 未报名，报名并返回报名信息Id
            // 信息插入到成绩表
            try {
                if (signUpService.add(studentId, eventId) < 1)
                    throw new InsertError();
            } catch (InsertError insertError) {
                insertError.printStackTrace();
            }
            return eventMapper.signUp(studentId, eventId);
        }
        return -1;
    }

    public List<Integer> signUpEvents(int studentId) {
        return eventMapper.selectSignUpEvents(studentId);
    }

    public Student getEventDetails(int studentId) {
        return studentMapper.signUpEventsDetails(studentId);
    }

    public int cancelRegistry(int studentId, int eventId) {
        // 将信息从成绩表中删除
        try {
            if (signUpService.del(studentId, eventId) < 1)
                throw new InsertError();
        } catch (InsertError error) {
            error.printStackTrace();
        }
        return eventMapper.cancelRegistry(studentId, eventId);
    }

    public Event getParticipants(int eventId) {
        return eventMapper.getParticipants(eventId);
    }

}
